package com.hatricks.is.base.threadpool;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @packageName: com.hatricks.base.threadpool
 * @className: ThreadUtils
 * @author: yanyh yanyh@glodon.com
 * @date: 2023/7/25 14:08
 * @description:
 */
@SuppressWarnings("LoggingSimilarMessage")
@Slf4j
public class ThreadPoolUtils {
    public static ThreadPoolExecutor createThreadPoolExecutor(int threadCount, String namePrefix) {
        ThreadFactory tf = ThreadUtil.newNamedThreadFactory(namePrefix, Boolean.TRUE);
        return new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), tf);
    }


    public static void printThreadPoolStatus(ThreadPoolExecutor threadPool, String poolName) {
        // 守护线程池 不影响停机
        ThreadFactory tf = ThreadUtil.newNamedThreadFactory("print-thread-pool-status", Boolean.TRUE);
        ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1, tf);
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            if (!threadPool.getQueue().isEmpty()) {
                log.info("=================================");
                log.info("线程池的名字为:[{}]", poolName);
                log.info("线程池核心线程数为: [{}]", threadPool.getPoolSize());
                log.info("线程池正在执行任务的线程数为:[{}]", threadPool.getActiveCount());
                log.info("线程池完成的任务数为: [{}]", threadPool.getCompletedTaskCount());
                log.info("线程池任务队列长度为: [{}]", threadPool.getQueue().size());
                log.info("=================================");

            }
        }, 0, 5, TimeUnit.SECONDS);
    }


    public static void main(String[] args) {

    }

}
